package com.qing.springbootorderservice.service;

import cn.hutool.http.HttpUtil;
import com.qing.springbootorderservice.dao.OrderDataBaseService;
import com.qing.springbootorderservice.pojo.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;

@Service
public class OrderService {

    @Autowired
    private OrderDataBaseService orderDataBaseService;

	//创建订单
	@Transactional(rollbackFor = Exception.class) //订单创建整个方法添加事务
	public void createOrder(Order order) throws Exception {
	    //1.订单信息-插入订单系统，订单数据库事务
        orderDataBaseService.saveOrder(order);
        //2.通过HTTP接口发送订单信息到运单系统
        String result=dispatchHttpApi(order.getOrderId());
        if(!"success".equals(result)){
            throw new Exception("订单创建失败，原因是运单接口调用失败！");
        }
    }

    /**
     * 模拟HTTP 请求接口发送，运单系统，将订单号传过去 SpringCloud
     * @param orderId
     * @return
     */
    private String dispatchHttpApi(String orderId) throws Exception{
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("orderId", orderId);
        return HttpUtil.get("http://localhost:8080/dispatch/order", paramMap,2000);
    };

}
